package com.huidz.calendar.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.transition.Slide;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.huidz.calendar.R;
import com.huidz.calendar.model.UserModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.Url;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class SubmitActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView comeback;

    private EditText edit_submit;
    private ImageView addimg;
    private RelativeLayout submit;

    private String url = "";//用于获取用户选择的图片路径


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slide slide = new Slide(Gravity.RIGHT);
        slide.setDuration(200L);//间歇时间
        getWindow().setEnterTransition(slide);
        setContentView(R.layout.activity_submit);
        inti();
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        comeback = findViewById(R.id.title_comeback);
        comeback.setOnClickListener(this);
        submit = findViewById(R.id.submit);
        submit.setOnClickListener(this);
        addimg = findViewById(R.id.addimg);
        addimg.setOnClickListener(this);
        edit_submit = findViewById(R.id.edit_submit);
    }

    public String substr;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_comeback:
                onBackPressed();
                break;

            case R.id.submit:
                substr = edit_submit.getText().toString();
                if (!edit_submit.getText().equals("")) {
                    lost();
                    okHttp_postFromParameters();
                } else {
                    Apiutils.SetToast(SubmitActivity.this, "请输入反馈内容");
                }
                break;

            case R.id.addimg:
                lost();
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 2);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                addimg.setImageURI(uri);
                url = uri.toString();
            }
        }
    }

    public void lost() {
        edit_submit.setFocusable(false);
        edit_submit.setFocusableInTouchMode(false);
        edit_submit.requestFocus();
        if (isSoftShowing()) {
            final View v = getWindow().peekDecorView();
            if (v != null && v.getWindowToken() != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }

    private boolean isSoftShowing() {
        //获取当屏幕内容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        //DecorView即为activity的顶级view
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
        //选取screenHeight*2/3进行判断
        return screenHeight * 2 / 3 > rect.bottom;
    }


    public void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("content", substr).add("img", url).add("logintoken", Url.USER_TOKEN)
                            .build();
                    Request request = new Request.Builder().url(Url.SUBMIT).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    public UserModel userm;
    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    Apiutils.SetLog("msg:" + msg.obj.toString());
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Apiutils.SetToast(SubmitActivity.this, msgs + "");
                        onBackPressed();
                    } else
                        Apiutils.SetToast(SubmitActivity.this, msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };
}
